import base64
import datetime
import sys

from PyQt5.QtCore import Qt, QObject, pyqtSignal
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QFrame, QHBoxLayout, QLabel, QRadioButton, QPushButton, \
    QLineEdit, QScrollArea, QListWidgetItem, QListWidget, QSizePolicy, QGridLayout, QMessageBox, QComboBox, \
    QTableWidget, QTableWidgetItem, QTextEdit
from PyQt5.QtGui import QPixmap
from client.client_socket import UserClient
from config import button_config,frame_config
from func import view,imgs,data,thred
from View.add_black_list import Blacklist
from config import button_config,Text_config,list_item_config,input_config
from information_shops import  Information_shops

class AI_ans(QObject):
    data_updated = pyqtSignal(str)


class admin_menu(QWidget):
    def __init__(self,parent=None):
        super().__init__()
        self.parent=parent
        self.client=self.parent.client
        self.user_name=self.client.username
        self.password=self.parent.client.password
        self.is_admin=self.parent.client.is_admin
        # self.client=UserClient()
        # self.user_name = '孙金淦'
        # self.password='123123123'
        # self.is_admin=1
        self.client.add_online(self.user_name)
        self.stop_event=None

        self.lis=[]
        self.ans=''
        self.is_ai=False
        self.is_new=True
        self.chat_update=False



        parser={
            'user_name':self.user_name,
        }
        data = self.client.get_user(parser).get('data')
        self.user_id = data.get('user_id')
        self.email = data.get('email')
        self.avatar = base64.b64decode(data.get('avatar'))
        self.resize(900, 900)

        self.ai_signal = AI_ans()
        self.ai_signal.data_updated.connect(self.update_ai_ans)
        self.ai_btn_statu=True

        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.setSpacing(0)
        self.initUI(main_layout)
    def initUI(self,main_layout):
        self.create_navigation_menu(main_layout)
        self.create_menu(main_layout)


    def create_navigation_menu(self,main_layout):
        frame=QFrame(self)
        frame.setStyleSheet("background-color:white;")
        frame.setFixedHeight(100)
        main_layout.addWidget(frame)
        layout = QHBoxLayout(frame)
        frame1=QFrame()
        layout.addWidget(frame1)
        frame1.setFixedWidth(250)
        logo = QLabel(frame1)
        img = QPixmap('../static/img/logo.png')
        img = img.scaled(100, 100, Qt.KeepAspectRatio)
        logo.setPixmap(img)


        frame2=QFrame()
        layout.addWidget(frame2)
        frame2.setFixedWidth(350)
        layout2=QHBoxLayout(frame2)
        for text in ['数据概览','商品管理','用户管理','AI助手']:
            btn1 = QPushButton(text)
            btn1.setStyleSheet(button_config.button_style7)
            btn1.setFixedSize(60,30)
            layout2.addWidget(btn1)
            btn1.clicked.connect(self._on_btn_clicked)

        frame3=QFrame()
        layout.addWidget(frame3)
        frame3.setFixedWidth(400)
        layout3=QHBoxLayout(frame3)
        self.push_input = QLineEdit()
        self.push_input.setPlaceholderText('你可以在这里输入你要推送的消息')
        self.push_input.setFixedSize(360,60)
        self.push_input.setStyleSheet(input_config.input_style5)
        layout3.addWidget(self.push_input)
    def create_menu(self,main_layout):
        self.frame=QFrame()
        self.frame.setContentsMargins(0,0,0,0)
        main_layout.addWidget(self.frame)
        layout=QHBoxLayout(self.frame)
        self.create_left_menu(layout)
        self.create_right_menu(layout)
    def create_left_menu(self,layout):
        self.left_frame = QFrame()
        self.left_frame.setStyleSheet("background-color:gray;")
        self.left_frame.setFixedWidth(250)
        layout.addWidget(self.left_frame)
    def create_right_menu(self,layout):
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        layout.addWidget(scroll_area)
        self.right_frame = QFrame()
        self.right_frame.setStyleSheet("background-color:#DCE3DB;")
        scroll_area.setWidget(self.right_frame)

#处理1
    def _on_btn_clicked(self):
        sender = self.sender()
        text=sender.text()
        if text=='商品管理':
            self.is_ai = False
            list=['时尚女装👠','运动男装👟','数码产品📱','休闲零食🍿','儿童玩具🧸','医疗健康💊','办公文具💼','化妆产品💄','材米油盐🍚','实用工具🔨']
            self.creat_left_scroll_list_item(text,list,self.item_double1_clicked)
        if text=='数据概览':
            self.is_ai = False
            list=['销售额统计','客流分析']
            self.creat_left_scroll_list_item(text,list,self.item_double2_clicked)
        if text=='用户管理':
            self.is_ai = False

            list=['正常用户','黑名单用户']
            self.creat_left_scroll_list_item(text,list,self.item_double3_clicked)
        if text=='AI助手':

            # self.is_ai=True
            parser={
                'user_id' : self.user_id,
            }
            list=['创建新会话']
            self.da=self.client.get_ai_history(parser)  # 会产生阻塞
            for i in range(len(self.da)):
                list.append(str(i))
            self.creat_left_scroll_list_item(text,list,self.item_double4_clicked)
            self.show_ai()
            if self.lis != []:
                self.show_history_ai()
            self.is_ai = True

#商品管理
    def item_double1_clicked(self,item):
        text=item.text()
        parse={
            'mode' :2,
            'category' : text
        }
        dic=self.client.get_shops(parse)
        if dic.get('code')==200:
            data=dic.get('data')
            self.show_shop(data)
#数据概览
    def item_double2_clicked(self,item):
        text=item.text()
        if text=='销售额统计':
            view.clear_layout(self.right_frame.layout())
            main_layout=self.right_frame.layout()
            if main_layout == None:
                main_layout=QVBoxLayout(self.right_frame)
            layout1 = QHBoxLayout()
            main_layout.addLayout(layout1)
            layout1.setSpacing(30)
            list1=['今日销售额','今日订单数','今日销售人数']
            for i in range(3):
                frame = QFrame()
                frame.setStyleSheet(frame_config.frame_style5)
                frame.setFixedSize(200,200)
                layout1.addWidget(frame)
                layout=QVBoxLayout(frame)
                parser = {
                    'mode': i+1,
                    'date': datetime.datetime.now().strftime('%Y-%m-%d')
                }
                response = self.client.get_data(parser)
                if i==0:
                    text='💵'+str(response.get('msg'))+'元'
                elif i==1:
                    text='🛒'+str(int(response.get('msg')))+'件'
                else:
                    text='🧔'+str(int(response.get('msg')))+'个'
                self.add_data_frame(layout,list1[i],text)

            frame = QFrame()
            frame.setStyleSheet(frame_config.frame_style5)
            frame.setMaximumHeight(600)
            main_layout.addWidget(frame)
            parser={
                'mode': 1,
            }
            layout=QVBoxLayout(frame)
            self.imgs_analysis(layout,'http://127.0.0.1:8000/data_analysis_api/get_value',parser)

            frame = QFrame()
            frame.setStyleSheet(frame_config.frame_style5)
            frame.setMaximumHeight(600)
            main_layout.addWidget(frame)
            parser = {
                'mode': 2,
            }
            layout = QVBoxLayout(frame)
            self.imgs_analysis(layout, 'http://127.0.0.1:8000/data_analysis_api/get_value',parser)

        if text=='客流分析':
            view.clear_layout(self.right_frame.layout())
            main_layout = self.right_frame.layout()
            if main_layout == None:
                main_layout = QVBoxLayout(self.right_frame)
            frame=QFrame()
            frame.setFixedHeight(600)
            frame.setStyleSheet(frame_config.frame_style1)
            main_layout.addWidget(frame)
            layout=QVBoxLayout(frame)
            layout1 = QHBoxLayout()
            layout.addLayout(layout1)
            self.input_user_name = QLineEdit()
            self.input_user_name.setPlaceholderText('请输入用户名')
            self.input_user_name.setFixedHeight(50)
            layout1.addWidget(self.input_user_name)
            search_btn=QPushButton()
            search_btn.setText('🔍')
            search_btn.setFixedSize(70,50)
            layout1.addWidget(search_btn)
            search_btn.clicked.connect(self.search_user)

            frame = QFrame()
            layout.addWidget(frame)
            frame.setStyleSheet(frame_config.frame_style2)
            frame.setMaximumHeight(500)
            self.layout_user=QHBoxLayout(frame)
            label=QLabel()
            label.setText('你可以在上方搜索栏查找用户，并看他详细信息')
            label.setAlignment(Qt.AlignCenter)
            label.setStyleSheet(Text_config.text_style2)
            self.layout_user.addWidget(label)
#用户管理
    def item_double3_clicked(self,item):
        text=item.text()
        users=self.client.get_all_user().get('data')
        if text=='正常用户':
            users=data.get_no_blacklist(users)
            self.show_user(users, 1)
        elif text=='黑名单用户':
            users=data.get_blacklist(users)
            self.show_user(users,2)
#AI助手
    def item_double4_clicked(self,item):
        if self.stop_event != None:
            self.stop_event.set()
            self.stop_event = None
            self.add_chat_to_sql()
        text=item.text()
        if text=="创建新会话":
            self.is_new=True
            self.show_ai()
        else:
            self.chat_update = False
            self.is_new=False
            id=int(text)
            self.origin=self.da[id].get('data')
            self.lis=self.da[id].get('data')
            self.ai_chat_id=self.da[id].get('id')
            self.show_ai()
            self.show_history_ai()
#ai问答页面
    def show_ai(self):
        view.clear_layout(self.right_frame.layout())
        main_layout = self.right_frame.layout()
        if main_layout == None:
            main_layout = QVBoxLayout(self.right_frame)

        main_layout.setSpacing(20)
        layout = QHBoxLayout()
        main_layout.addLayout(layout)
        self.input_query = QLineEdit()
        layout.addWidget(self.input_query)
        self.input_query.setStyleSheet(input_config.input_style8)
        self.input_query.setFixedHeight(60)
        self.input_query.setPlaceholderText("你想问什么")
        self.ai_btn = QPushButton()
        if self.ai_btn_statu == True:
            self.ai_btn.setText('🔍')
        else:
            self.ai_btn.setText('⏹️')
        self.ai_btn.setFixedSize(60, 60)
        self.ai_btn.setStyleSheet(button_config.button_style2)
        layout.addWidget(self.ai_btn)
        self.ai_btn.clicked.connect(self.query_clicked)

        que_frame = view.create_scroll(main_layout)
        que_frame.setStyleSheet(frame_config.frame_style3)
        self.que_layout = QVBoxLayout(que_frame)
    # #加载历史ai聊天页面
    def show_history_ai(self):
        for tem in self.lis:
            user=tem.get('user')
            ai=tem.get('ai')
            self.show_user_question(user)
            self.show_ai_ans(ai)
    #将会话内容插入数据表
    def add_chat_to_sql(self):
        if self.lis != []:
            if self.is_new:
                parser = {
                    'user_id': self.user_id,
                    'date': datetime.datetime.now().strftime('%Y-%m-%d %H:%M'),
                    'data': self.lis
                }
                self.client.save_chat_ai(parser)
            else:
                if self.chat_update:
                    parser = {
                        'user_id': self.user_id,
                        'date': datetime.datetime.now().strftime('%Y-%m-%d %H:%M'),
                        'data': self.lis,
                        'id': self.ai_chat_id
                    }
                    self.client.add_ai_chat_history(parser)
            self.lis=[]
    #将用户信息展示到前端,mode为1为正常用户，mode2为黑名单用户
    def show_user(self,data,mode):
        num = len(data)
        view.clear_layout(self.right_frame.layout())
        main_layout = self.right_frame.layout()
        if main_layout == None:
            main_layout = QVBoxLayout(self.right_frame)
        frame = QFrame()
        main_layout.addWidget(frame)

        layout0 = QGridLayout(frame)
        layout0.setColumnStretch(0, 1)
        layout0.setColumnStretch(1, 1)
        layout0.setColumnStretch(2, 1)

        for index in range(num):
            frame = QFrame()
            frame.setFixedSize(230, 280)
            frame.setStyleSheet("background-color:white;")
            layout0.addWidget(frame)
            username = data[index].get('username')
            email = data[index].get('email')
            id = data[index].get('userid')
            password = data[index].get('password')
            avatar = base64.b64decode(data[index].get('avatar'))
            layout1 = QVBoxLayout(frame)
            img_label = QLabel()
            img = QPixmap()
            img.loadFromData(avatar)
            img = img.scaled(120, 120, Qt.KeepAspectRatio)
            img_label.setPixmap(img)
            img_label.setAlignment(Qt.AlignCenter)
            layout1.addWidget(img_label)

            label = QLabel()
            text=f'id:{id},用户名{username}'
            label.setText(text)
            label.setStyleSheet(Text_config.text_style2)
            layout1.addWidget(label)
            label = QLabel()
            text = f'邮箱:{email}'
            label.setText(text)
            layout1.addWidget(label)

            send_mes = QPushButton()
            send_mes.setText('发信息')
            send_mes.setStyleSheet(button_config.button_style2)
            send_mes.setProperty("user_id", id)
            send_mes.setProperty("username", username)
            send_mes.clicked.connect(self.push_message_btn_clicked)
            layout1.addWidget(send_mes)
            if mode==1:
                add_blacklist_btn = QPushButton()
                add_blacklist_btn.setText('拉黑')
                add_blacklist_btn.setStyleSheet(button_config.button_style4)
                add_blacklist_btn.setProperty("user_id", id)
                layout1.addWidget(add_blacklist_btn)
                add_blacklist_btn.clicked.connect(self.add_blacklist)
            if mode==2:
                add_blacklist_btn = QPushButton()
                add_blacklist_btn.setText('洗白')
                add_blacklist_btn.setStyleSheet(button_config.button_style4)
                add_blacklist_btn.setProperty("user_id", id)
                layout1.addWidget(add_blacklist_btn)
                add_blacklist_btn.clicked.connect(self.add_whitelist)
    #将商品信息展示到前端
    def show_shop(self,data):
        num=len(data)
        view.clear_layout(self.right_frame.layout())
        main_layout = self.right_frame.layout()
        if main_layout == None:
            main_layout=QVBoxLayout(self.right_frame)
        frame = QFrame()
        main_layout.addWidget(frame)

        layout0 = QGridLayout(frame)
        layout0.setColumnStretch(0, 1)
        layout0.setColumnStretch(1, 1)
        layout0.setColumnStretch(2, 1)

        for index in range(num):
            frame=QFrame()
            frame.setFixedSize(230,280)
            frame.setStyleSheet("background-color:white;")
            layout0.addWidget(frame)
            shop_name=data[index].get('shop_name')
            seller_name=data[index].get('sellername')
            id=data[index].get('ID')
            price=data[index].get('price')
            brand=data[index].get('brand')
            num=data[index].get('num')
            description=data[index].get('description')
            avatar=base64.b64decode(data[index].get('avatar'))
            layout1 = QVBoxLayout(frame)
            text=f'卖家：{seller_name},品牌：{brand},介绍:{description}'
            frame.setToolTip(text)

            img_label=QLabel()
            img = QPixmap()
            img.loadFromData(avatar)
            img = img.scaled(120, 120, Qt.KeepAspectRatio)
            img_label.setPixmap(img)
            img_label.setAlignment(Qt.AlignCenter)
            layout1.addWidget(img_label)

            label=QLabel()
            label.setText(shop_name)
            label.setStyleSheet(Text_config.text_style2)
            layout1.addWidget(label)

            label = QLabel()
            text = f'商品id:{str(id)}'
            label.setText(text)
            layout1.addWidget(label)

            label=QLabel()
            text=f'价格:{str(price)}'
            label.setText(text)
            layout1.addWidget(label)

            label = QLabel()
            text = f'库存量:{str(num)}'
            label.setText(text)
            layout1.addWidget(label)

            information_btn=QPushButton()
            information_btn.setProperty("sellername", data[index].get('sellername'))
            information_btn.setProperty("shop_name", data[index].get('shop_name'))
            information_btn.setProperty("shop_id", id)
            information_btn.setText('查看报表')
            information_btn.setStyleSheet(button_config.button_style2)
            layout1.addWidget(information_btn)
            information_btn.clicked.connect(self.information_shops_btn)

            delete_btn=QPushButton()
            delete_btn.setProperty("sellername", data[index].get('sellername'))
            delete_btn.setProperty("shop_name", data[index].get('shop_name'))
            delete_btn.setText('删除')
            delete_btn.setStyleSheet(button_config.button_style4)
            layout1.addWidget(delete_btn)
            delete_btn.clicked.connect(self.delete_shop_btn)
    def delete_shop_btn(self):
        ret = QMessageBox.question(None, "提问", "确定要删除吗", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if ret == QMessageBox.Yes:
            sender=self.sender()
            seller_name=sender.property('sellername')
            shop_name=sender.property('shop_name')
            self.delete_shop(seller_name,shop_name)
        else:
            return
    #查看报表信息
    def information_shops_btn(self):
        sender=self.sender()
        seller_name=sender.property('sellername')
        self.shop_name=sender.property('shop_name')
        self.shop_id=sender.property('shop_id')
        information=Information_shops(self)
        res =information.exec_()
    #删除商品
    def delete_shop(self,seller_name,shop_name):
        parser={
            'shop_name':shop_name,
            'seller_name':seller_name,
        }
        dic=self.client.delete_shop(parser)
    #创建左边含滑动框的列表容器
    def creat_left_scroll_list_item(self,text,list,func):
        view.clear_layout(self.left_frame.layout())
        view.clear_layout(self.right_frame.layout())
        layout = self.left_frame.layout()
        if layout is None:
            layout = QVBoxLayout(self.left_frame)
        label = QLabel()
        label.setText(text)
        label.setStyleSheet(Text_config.text_style2)
        layout.addWidget(label)
        scroll = QScrollArea()
        scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        scroll.setWidgetResizable(True)
        layout.addWidget(scroll)
        frame = QFrame()
        scroll.setWidget(frame)
        frame.setStyleSheet("background-color:white;")
        layout1 = QVBoxLayout(frame)
        list_item = QListWidget()
        layout1.addWidget(list_item)
        list_item.setStyleSheet(list_item_config.list_item_style1)
        for text in list:
            item = QListWidgetItem()
            item.setText(text)
            list_item.addItem(item)
        list_item.itemDoubleClicked.connect(func)
    #向展示数据的容器添加数据
    def add_data_frame(self,layout,text1,text2):
        label = QLabel()
        label.setText(text1)
        label.setStyleSheet(Text_config.text_style2)
        layout.addWidget(label)
        label = QLabel()
        label.setText(text2)
        label.setStyleSheet(Text_config.text_style3)
        layout.addWidget(label)
    #获取后端的数据分析可视化结果并输出到前端,w,h如果存在则会修改获取图片的大小，mode如果为1会添加部分文本
    def imgs_analysis(self,layout2,url,parser,w=None,h=None,mode=None):
        data=self.client.get_view(url,parser)
        if not data.get('img'):
            label=QLabel()
            text=data.get('msg')
            label.setText(text)
            label.setStyleSheet(Text_config.text_style3)
            layout2.addWidget(label)
            return
        if mode==1:
            l=QLabel()
            text=f"用户总销售额：{data.get('seller_sum')}"
            l.setText(text)
            l.setStyleSheet(Text_config.text_style3)
            layout2.addWidget(l)

            l=QLabel()
            text=f"用户总购买额：{data.get('buy_sum')}"
            l.setText(text)
            l.setStyleSheet(Text_config.text_style3)
            layout2.addWidget(l)
        img_label = QLabel()
        img_label.setAlignment(Qt.AlignCenter)
        layout2.addWidget(img_label)
        avatar = base64.b64decode(data.get('img'))
        if w and h:
            avatar=imgs.resize_(avatar,w,h)
        img = QPixmap()
        if img.loadFromData(avatar):
            img_label.setPixmap(img)
        else:
            print("图片加载失败：无效的图片数据")
    #展示用户详细信息
    def search_user(self):
        user_name = self.input_user_name.text()
        parser={
            'user_name':user_name,
        }
        dic=self.client.get_user(parser)
        if dic['code']==200:
            self.user_id=dic['data']['user_id']
            parser={
                'user_id' : self.user_id,
                'result_mode':1
            }
            dic1=self.client.get_user(parser)
            view.clear_layout(self.layout_user)
            frame = QFrame()
            self.layout_user.addWidget(frame)
            frame.setStyleSheet(frame_config.frame_style1)
            frame.setFixedWidth(300)

            layout=QVBoxLayout(frame)
            self.user_frame = QFrame()
            self.layout_user.addWidget(self.user_frame)
            self.user_frame.setStyleSheet(frame_config.frame_style1)
            self.user_frame.setFixedWidth(400)
            parser={
                'user_id' : self.user_id,
                'result_mode':1
            }
            dic1=self.client.get_user_some_data(parser)
            try:
                date=datetime.datetime.strptime(dic1.get('date'),'%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d')
            except:
                date=dic.get('date')
            sum=dic1.get('sum')
            count=dic1.get('count')
            avatar=base64.b64decode(dic.get('data').get('avatar'))
            email=dic.get('data').get('email')
            is_blacklist=dic.get('is_blacklist')
            if is_blacklist==1:
                statu='黑名单用户'
            else:
                statu='正常用户'
            img_label=QLabel()
            img=QPixmap()
            if img.loadFromData(avatar):
                img_label.setPixmap(img)
            img_label.setAlignment(Qt.AlignCenter)
            layout.addWidget(img_label)
            for i in [f'用户名：{self.input_user_name.text()}',f'用户邮箱：{email}',f'用户最近消费日期：{date}',f'用户消费总金额：{str(sum)}',f'用户购买商品总量：{str(count)}',f'用户状态：{statu}']:
                label = QLabel()
                label.setText(i)
                label.setStyleSheet(Text_config.text_style3)
                layout.addWidget(label)
            self.combo=QComboBox()
            layout.addWidget(self.combo)
            for i in ['用户销售与购买金额比例图','用户购买记录','用户售出记录']:
                self.combo.addItem(i)
            self.combo_changed()
            self.combo.currentTextChanged.connect(self.combo_changed)


        else:
            QMessageBox.critical(None,'错误','不存在该用户')
    #选择查看单个用户分析
    def combo_changed(self):
        view.clear_layout(self.user_frame.layout())
        layout=self.user_frame.layout()
        if layout is None:
            layout = QVBoxLayout(self.user_frame)
        text=self.combo.currentText()
        if text=='用户销售与购买金额比例图':
            l=QLabel()
            l.setText(text)
            l.setStyleSheet(Text_config.text_style3)
            layout.addWidget(l)

            parser={
                'user_id':self.user_id,
            }
            url='http://127.0.0.1:8000/data_analysis_api/buy_div_seller'
            self.imgs_analysis(layout,url,parser,300,300,1)
        if text=='用户购买记录':
            result_mode =2
            labels=["日期", "商品名", "数量"]
            self.create_tabel(layout, text, result_mode, labels)
        if text=='用户售出记录':
            result_mode=3
            labels = ["商品id", "商品名", "数量"]
            self.create_tabel(layout,text,result_mode,labels)
    #加入黑名单
    def add_blacklist(self):
        sender=self.sender()
        self.client_id=sender.property('user_id')
        my = Blacklist(self)
        my.exec_()
        # parser={
        #     'user_id':user_id,
        #     'statu':1,
        # }
        # self.client.update_blacklist(parser)
    #加入白名单
    def add_whitelist(self):
        sender=self.sender()
        user_id=sender.property('user_id')
        parser={
            'user1id':user_id,
            'statu':False,
        }
        self.client.update_blacklist(parser)
    #询问ai问题
    def query_clicked(self):
        if self.ai_btn_statu==True:
            query=self.input_query.text()
            self.show_user_question(query)
            self.ai_btn.setText('⏹️')
            self.ai_btn_statu=False

            self.show_ai_ans('.....正在思考中')
            if query:
                chat={'user':query,'ai':'.....正在思考中'}
                self.lis.append(chat)
                parser={
                    "query": query
                }
                self.stop_event=thred.star_thread(thred.query_ai,self.client,parser,'',self.ai_signal)


        else:
            self.ai_btn.setText('🔍')
            self.ai_text.setText('已停止思考')
            self.lis[-1]['ai'] = '已停止思考'
            if self.stop_event != None:
                self.stop_event.set()
                self.stop_event = None
            self.ai_btn_statu=True

            # ans=self.client.query_ai(parser)
            # print(ans)
    #将用户的问题输出到页面
    def show_user_question(self,text1):
        layout = QHBoxLayout()


        self.que_layout.addLayout(layout)
        label = QLabel('🧔:')
        label.setStyleSheet(Text_config.text_style4)
        text = QTextEdit()
        text.setText(text1)
        text.setReadOnly(True)
        text.setStyleSheet(input_config.input_style3)
        text.setFixedHeight(50)
        layout.addWidget(label)
        layout.addWidget(text)
    #将ai的回答输入到页面
    def show_ai_ans(self,text1):
        layout = QHBoxLayout()
        self.que_layout.addLayout(layout)
        label = QLabel(':🤖')
        label.setStyleSheet(Text_config.text_style4)
        self.ai_text = QTextEdit()
        self.ai_text.setText(text1)
        self.ai_text.setReadOnly(True)
        self.ai_text.setStyleSheet(input_config.input_style3)
        self.ai_text.setFixedHeight(50)
        layout.addWidget(self.ai_text)
        layout.addWidget(label)
    #侦察ai回答是否完成
    def update_ai_ans(self,data):
        self.lis[-1]['ai']=data

        self.chat_update=True
        self.ai_btn_statu = True
        if self.is_ai == True:
            self.ai_text.setText(data)
            self.ai_btn.setText('🔍')
    #消息推送
    def push_message_btn_clicked(self):
        mes=self.push_input.text()
        if mes=='':
            return
        else:
            sender=self.sender()
            user2id=sender.property('user_id')
            username=sender.property('username')
            text=f'确定向用户{username}发送消息，内容：{mes}'
            res=QMessageBox.question(None,'提问',text,QMessageBox.Yes | QMessageBox.No,QMessageBox.No)
            if res:
                parser={
                    'sender_id' : self.user_id,
                    'receiver_id' : user2id,
                    'message' : mes,
                    'datetime' : datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                }
                self.client.send_chat(parser)
            else:
                pass
    # 向layout布局中添加表格
    def create_tabel(self,layout,text,result_mode,labels):
        l = QLabel()
        l.setText(text)
        l.setStyleSheet(Text_config.text_style3)
        layout.addWidget(l)

        parser = {
            'user_id': self.user_id,
            'result_mode': result_mode
        }
        tem=self.client.get_user_some_data(parser)
        history_list =tem.get('history_lis')
        frame = view.create_scroll(layout)
        layout = QVBoxLayout(frame)
        view.create_tabel(layout, labels, history_list)
    def closeEvent(self,event):
        if self.stop_event != None:
            self.stop_event.set()
            self.stop_event = None
        self.add_chat_to_sql()
        self.client.logout(self.user_name)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = admin_menu()
    win.show()
    sys.exit(app.exec_())